var http = require('http');
var relation = require('./proxy/relation');
var faction = require('./proxy/factionmember');
var logger = require('./service/Logger');

logger.debug('关系维护进程启动...')

process.on('message', function(data){
    console.log(data)
    if(data.faction){
        addFactionRelations(data, function(){
            process.send({returnMsg: '添加圈子成员关系'})
        })
    }else{
        addAttendsRelations(data, function(){
            process.send({returnMsg: '添加出席者关系'})
        })
    }
});
process.on('SIGHUP', function() {
    console.log('子进程退出...')
    process.exit();//收到kill信息，进程退出
});

/**
 * 处理添加关系
 * @param data
 * @param callback
 */
function addAttendsRelations(data, callback){
    var attends = data.attends,
        userId = data.userId;
    attends.forEach(function(targetUser){
        if(targetUser && targetUser.id){
            relation.addRelationWeight(targetUser.id, userId, 1, function(err, data){
                if(err) logger.error(err.message);
                logger.debug('['+targetUser.id+'] and ['+userId+'] add relation ---- '+1);
            })
        }
    })
    callback()
}
function addFactionRelations(data, callback){
    var factionId = data.factionId,
        userId = data.userId;
    faction.getAllMembers(factionId, function(err, fms){
        if(err) return callback(err)
        fms.forEach(function(fm){
            if(fm && fm.member && fm.member.id){
                relation.addRelationWeight(userId, fm.member.id, 10, function(err, resp){
                    if(resp)
                        console.log('完成圈关系增加:'+resp);// 完成
                })
            }
        });
        callback();
    })
}